from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
import uvicorn
import asyncio
from concurrent.futures import ThreadPoolExecutor
# 数据库初始化相关
from auth.db import Base, engine, SessionLocal
from auth import models, utils
# 路由模块
from auth import routers as auth_router
from auth import profile_router               # 个人信息路由
from devices import routers as device_router
from ecg import routers as ecg_router
from patients import routers as patient_router   # ← 修正:绑定 patient 路由
from alert import routers as alert_router
from ai.routers import router as ai_router

# ========== 性能优化1: 扩大线程池用于CPU密集型任务 ==========
# 默认线程池太小(通常只有CPU核心数)，增加到50可以并发处理更多bcrypt任务
asyncio.get_event_loop().set_default_executor(
    ThreadPoolExecutor(max_workers=50)  # 关键优化：增加线程池大小
)

# -------------------------------------------------------------------
# 创建应用
# -------------------------------------------------------------------
app = FastAPI(title="可穿戴心电监测平台")

# Session 用于验证码
app.add_middleware(SessionMiddleware, secret_key="supersecretkey123")

# 静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# -------------------------------------------------------------------
# 初始化数据库 + 超级管理员
# -------------------------------------------------------------------
Base.metadata.create_all(bind=engine)

def init_superadmin():
    db = SessionLocal()
    if not db.query(models.User).filter(models.User.role == "superadmin").first():
        superadmin = models.User(
            username="root",
            password=utils.hash_password("111111"),
            email="superadmin@system.com",
            phone="13900000000",
            role="superadmin"
        )
        db.add(superadmin)
        db.commit()
    db.close()

init_superadmin()

# -------------------------------------------------------------------
# 注册所有路由
# -------------------------------------------------------------------
app.include_router(ecg_router.router)         # 心电数据 / 上传 / 查看
app.include_router(auth_router.router)        # 登录 / 注册 / 用户管理
app.include_router(profile_router.router)     # 个人信息
app.include_router(device_router.router)      # 设备管理
app.include_router(patient_router.router)     # 医生管理患者（这一行你之前漏了）
app.include_router(alert_router.router)


app.include_router(ai_router)

# -------------------------------------------------------------------
# main 结束

# -------------------------------------------------------------------

# main.py


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        workers=8,              # 8个worker进程（根据CPU核心数）
        limit_concurrency=1000,  # 提高最大并发到1000
        backlog=4096,           # 提高backlog到4096
        timeout_keep_alive=10,  # 减少keep-alive超时
        access_log=False        # 关闭访问日志（减少IO）
    )